﻿using Learun.Loger;
using Learun.Util;
using System.Diagnostics;
using System.Globalization;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace Learun.Application.Web
{
    public class TimingActionFilter : ActionFilterAttribute
    {
        private const string Key = "__action_duration__";
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var stopWatch = new Stopwatch();

            actionContext.Request.Properties[Key] = stopWatch;
            stopWatch.Start();
        }

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            if (!actionExecutedContext.Request.Properties.ContainsKey(Key))
            {
                return;
            }
            var stopWatch = actionExecutedContext.Request.Properties[Key] as Stopwatch;
            if (stopWatch == null)
            {
                return;
            }
            stopWatch.Stop();
            var actionDescriptor = actionExecutedContext.ActionContext.ActionDescriptor;
            var actionName = actionDescriptor.ActionName;
            var controllerName = actionDescriptor.ControllerDescriptor.ControllerName;
            if (actionExecutedContext.Response != null)
            {
                var _logger = LogFactory.GetLogger("监听Action运行时间");
                var userInfo = LoginUserInfo.Get();
                _logger.Warn(controllerName + "-" + actionName + " 运行时长:" + stopWatch.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture));
                if (userInfo != null)
                {                                                                             
                    _logger.Warn("  |   用户名称:" + userInfo.realName + "," + "IP地址:" + userInfo.iPAddress + "\r\n");
                }

                //actionExecutedContext.Response.Content.Headers.Add("TotalSpendTimes", stopWatch.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture));
            }
        }
    }
}